<?
/**
 * Template Name: Payment
 */
wp_cache_post_change( get_the_ID() );
$venue = $_POST['form_venue'];
$pitch = $_POST['form_pitch'];
$slot = $_POST['form_slot'];
$date = $_POST['form_date'];
$price = get_field('price',$slot) * 0.95;
$userID = $_POST['form_user'];

if ($_POST['form_email']) {
    $userID = wp_create_user($_POST['form_email'], $_POST['form_password'], $_POST['form_email']);
    wp_update_user( array ('ID' => $userID, 'first_name' => $_POST['form_first'], 'last_name' => $_POST['form_last']) ) ;

    $field_key = "field_517436d75c29a"; //Phone
    $value = $_POST['form_phone'];
    update_field($field_key, $value, 'user_'.$userID);

    $field_key = "field_5140cf2f66631"; //Team
    $value = $_POST['form_team'];
    update_field($field_key, $value, 'user_'.$userID);

    $creds = array();
    $creds['user_login'] = $_POST['form_email'];
    $creds['user_password'] = $_POST['form_password'];
    $creds['remember'] = true;
    $user = wp_signon( $creds, false );
    if ( is_wp_error($user) ) {
        echo $user->get_error_message();
    }
}

get_header(); ?>

<script type="text/javascript">
    var PAYMILL_PUBLIC_KEY = '07297858825fad6df8df7595644cc080';
</script>

<div class="container">
    <? while (have_posts()) : the_post(); ?>

    <?
    /*
        <input type="hidden" name="form_venue" value="<? echo $venue ?>">
        <input type="hidden" name="form_pitch" value="<? echo $pitch ?>">
        <input type="hidden" name="form_slot" value="<? echo $slot ?>">
        <input type="hidden" name="form_date" value="<? echo $date ?>">
        <input type="hidden" name="form_user" value="<? echo $userID ?>">
     */
    ?>

    <div>
        <h1>Payment Processing</h1>

        <div class="row-fluid">
            <div class="span8">
                <div class="card grey clearfix">
                    <h2 class="title">Card Details</h2>


                    <!-- START: Payment form -->
                    <div class="controls">
                            <div class="payment-errors text-error"></div>
                    </div>
                    <div class="clearfix"></div>
                    <div class="well clearfix" style="background:white">
                        <!--
                        <div class="controls controls-row">
                        <div class="btn-group span4">
                            <button id="btn-paymenttype-cc"  class="paymenttype btn btn-primary disabled" value="cc">Credit card</button>
                            <!--<button id="btn-paymenttype-elv" class="paymenttype btn" value="elv">ELV</button>-->
                            <!--</div><br /><br />
                        </div>-->

                        <div class="alert alert-success" style="text-align: center;">
                            <strong>We accept credit cards from all major suppliers.</strong>
                        </div>

                        <div style="text-align: center;margin-bottom:20px;">
                            <img src="<?php echo get_template_directory_uri(); ?>/img/card%20logos.png" style="width: 300px;margin:auto;"/>
                        </div>

                        <form class="form-horizontal" id="payment-form" action="/authorise/" method="POST">

                            <input type="hidden" name="form_venue" value="<? echo $venue ?>">
                            <input type="hidden" name="form_pitch" value="<? echo $pitch ?>">
                            <input type="hidden" name="form_slot" value="<? echo $slot ?>">
                            <input type="hidden" name="form_date" value="<? echo $date ?>">
                            <input type="hidden" name="form_user" value="<? echo $userID ?>">
                            <input type="hidden" name="form_price" value="<? echo $price ?>">

                            <div class="clearfix"></div>
                            <div id="payment-form-cc">
                                <input class="card-amount-int" type="hidden" value="<? echo str_replace('.', '', $price) ?>"/>
                                <input class="card-currency" type="hidden" value="GBP"/>

                                <div class="control-group">
                                    <label class="control-label">Card number</label>
                                    <div class="controls">
                                        <input class="card-number" type="text" size="20" value="4111111111111111"/>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label">CVC</label>
                                    <div class="controls">
                                        <input class="card-cvc span2" type="text" size="4" value="111"/>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label">Card holder</label>
                                    <div class="controls">
                                        <input class="card-holdername" type="text" size="20" value="Max Mustermann"/>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label">Valid until (MM/YYYY)</label>
                                    <div class="controls controls-row">
                                        <input class="card-expiry-month span2" type="text" size="2" value="12"/>
                                        <span> / </span>
                                        <input class="card-expiry-year span2" type="text" size="4" value="2015"/>
                                    </div>
                                </div>

                            </div>
                            <div class="controls">
                                <div class="span3">
                                    <button class="submit-button btn btn-primary" type="submit">Submit &raquo;</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <!-- END: Payment form -->

                </div>
            </div>
            <div class="span4">
                <div class="card grey">
                    <h2 class="title">Booking Information</h2>

                    <table class="table table-striped table-condensed">
                        <tbody>
                        <tr>
                            <th>Venue</th>
                            <td><? echo get_field('name', $venue) ?></td>
                        </tr>
                        <tr>
                            <th>Pitch</th>
                            <td><? echo get_field('pid', $pitch) ?></td>
                        </tr>
                        <tr>
                            <th>Date</th>
                            <td><? echo date('l, j F Y',strtotime($date)) ?></td>
                        </tr>
                        <tr>
                            <th>Start</th>
                            <td><? echo get_field('start_time', $slot) ?></td>
                        </tr>
                        <tr>
                            <th>End</th>
                            <td><? echo get_field('end_time', $slot) ?></td>
                        </tr>
                        <tr>
                            <th>Price</th>
                            <td><? echo '&pound;'.$price ?></td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <div class="card grey">
                    <h2 class="title">User Details</h2>
                    <?
                        //$userID = get_user_id();
                        $user_info = get_userdata($userID);
                    ?>

                    <table class="table table-striped table-condensed">
                        <tbody>
                        <tr>
                            <th>Name</th>
                            <td><? echo $user_info-> user_firstname.' '.$user_info-> user_lastname ?></td>
                        </tr>
                        <tr>
                            <th>Email</th>
                            <td><? echo $user_info-> user_email ?></td>
                        </tr>
                        </tbody>
                    </table>


                </div>

            </div>
        </div>


    </div>

    <? endwhile; ?>
</div>

<?php get_footer(); ?>

<script src="https://bridge.paymill.com/"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        function PaymillResponseHandler(error, result) {
            if (error) {
                // Show the error message above the form
                $(".payment-errors").text(error.apierror);
            } else {
                $(".payment-errors").text("");
                var form = $("#payment-form");
                // Token
                var token = result.token;
                // Insert token into the payment form
                form.append("<input type='hidden' name='paymillToken' value='" + token + "'/>");
                form.get(0).submit();
            }
            $(".submit-button").removeAttr("disabled");
        }

        $("#payment-form").submit(function (event) {
            // Deactivate the submit button to avoid further clicks
            $('.submit-button').attr("disabled", "disabled");
            if (false == paymill.validateCardNumber($('.card-number').val())) {
                $(".payment-errors").text("Invalid card number");
                $(".submit-button").removeAttr("disabled");
                return false;
            }

            if (false == paymill.validateExpiry($('.card-expiry-month').val(), $('.card-expiry-year').val())) {
                $(".payment-errors").text("Invalid date of expiry");
                $(".submit-button").removeAttr("disabled");
                return false;
            }

            paymenttype = $('.paymenttype.disabled').length ? $('.paymenttype.disabled').val() : 'cc';
            switch (paymenttype) {
                case "cc":
                    var params = {
                        amount_int:     $('.card-amount-int').val(),  // E.g. "15" for 0.15 Eur
                        //amount:         $('.card-amount').val(),    // deprecated!
                        currency:       $('.card-currency').val(),    // ISO 4217 e.g. "EUR"
                        number:         $('.card-number').val(),
                        exp_month:      $('.card-expiry-month').val(),
                        exp_year:       $('.card-expiry-year').val(),
                        cvc:            $('.card-cvc').val(),
                        cardholdername: $('.card-holdername').val()
                    };
                    break;

                case "elv":
                    var params = {
                        number:         $('.elv-account').val(),
                        bank:           $('.elv-bankcode').val(),
                        accountholder:  $('.elv-holdername').val()
                    };
                    break;
            }
            paymill.createToken(params, PaymillResponseHandler);

            return false;
        });

        // Toggle buttons and forms
        $(".paymenttype").click(function (event) {
            $(this).addClass('btn-primary disabled');
            $('#payment-form-cc').toggle();
            $('#payment-form-elv').toggle();
            if($(this).val()=='cc') {
                $('#btn-paymenttype-elv').removeClass('btn-primary disabled');
            }
            else {
                $('#btn-paymenttype-cc').removeClass('btn-primary disabled');
            }
        });
    });
</script>